package cn.sharp.bbs.service.impl;

import cn.sharp.bbs.common.TokenUtils;
import cn.sharp.bbs.common.Utils;
import cn.sharp.bbs.dao.security.LoginDao;
import cn.sharp.bbs.dao.gen.UserMapper;
import cn.sharp.bbs.entity.BO.LoginEntity;
import cn.sharp.bbs.entity.DO.User;
import cn.sharp.bbs.event.LoginEvent;
import cn.sharp.bbs.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Transactional
@Service
public class LoginServiceImpl implements LoginService, ApplicationEventPublisherAware {
    Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
    @Resource
    UserMapper userMapper;

    @Resource
    LoginDao loginDao;

    private ApplicationEventPublisher eventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    /**
     * 检查登陆信息, 并为其设置id
     * @param entity 登陆实体 包含 账号、密码
     * @return 返回是否成功
     */
    @Override
    public boolean checkLogin(LoginEntity entity) {
        // 获取账号
        String account = entity.getU_account();
        LoginEntity loginEntity;

        // 检查是邮箱登陆还是账号登陆, 并依此获取登陆实例
        if(Utils.isValidEmail(account)){
            loginEntity = loginDao.selectByMail(account);
        }else {
            loginEntity = loginDao.selectByAccount(account);
        }

        // 判断获取的实例列表非空时, 为传入实体设置id, 并返回密码是否正确
        if (loginEntity!=null){
            entity.setU_id(loginEntity.getU_id());
            entity.setU_account(loginEntity.getU_account());
            return entity.getU_pwd().equals(loginEntity.getU_pwd());
        }
        return false;
    }

    /**
     * 依据uid获取登陆实体
     * @param uid 用户id
     * @return 登陆实体
     */
    @Override
    public LoginEntity getLoginUserById(Long uid) {
        User user = userMapper.selectByPrimaryKey(uid);
        return new LoginEntity(user.getId(), user.getNum(), user.getPwd());
    }

    /**
     * 实际登陆操作
     * @param entity 登陆实体
     * @return 登陆后的token
     */
    @Override
    public String doLogin(LoginEntity entity) {
        eventPublisher.publishEvent(new LoginEvent(this, entity.getU_id()));
        return TokenUtils.loginSign(String.valueOf(entity.getU_id()), entity.getU_pwd());
    }
}